package com.learning.platform.controller;

import com.learning.platform.dto.*;
import com.learning.platform.enums.Difficulty;
import com.learning.platform.security.UserPrincipal;
import com.learning.platform.service.CourseService;
import com.learning.platform.service.LessonService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 课程控制器
 * 处理课程的CRUD操作和课程相关的课时管理功能
 */
@RestController
@RequestMapping("/api/v1/courses")
public class CourseController {
    
    private static final Logger logger = LoggerFactory.getLogger(CourseController.class);
    
    private final CourseService courseService;
    private final LessonService lessonService;
    
    /**
     * 构造函数，注入CourseService和LessonService
     * @param courseService 课程服务
     * @param lessonService 课时服务
     */
    public CourseController(CourseService courseService, LessonService lessonService) {
        this.courseService = courseService;
        this.lessonService = lessonService;
    }
    
    /**
     * 获取课程列表接口
     * 支持分页、关键词搜索、分类筛选、难度筛选、价格筛选和排序
     * @param page 当前页码，默认为1
     * @param pageSize 每页记录数，默认为10
     * @param keyword 搜索关键词
     * @param categoryId 分类ID
     * @param difficulty 难度级别
     * @param minPrice 最低价格
     * @param maxPrice 最高价格
     * @param sortBy 排序方式，默认为latest（最新）
     * @return 课程列表分页数据
     */
    @GetMapping
    public ApiResponse<Page<CourseResponse>> getCourses(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String difficulty,
            @RequestParam(required = false) String minPrice,
            @RequestParam(required = false) String maxPrice,
            @RequestParam(defaultValue = "latest") String sortBy) {
        
        // 构建搜索请求对象
        CourseSearchRequest searchRequest = new CourseSearchRequest();
        searchRequest.setPage(page);
        searchRequest.setPageSize(pageSize);
        searchRequest.setKeyword(keyword);
        searchRequest.setCategoryId(categoryId);
        searchRequest.setSortBy(sortBy);
        
        // 处理难度参数
        if (difficulty != null && !difficulty.isEmpty()) {
            try {
                searchRequest.setDifficulty(Difficulty.valueOf(difficulty.toUpperCase()));
            } catch (IllegalArgumentException e) {
                // 忽略无效的难度值
            }
        }
        
        // 处理价格参数
        if (minPrice != null && !minPrice.isEmpty()) {
            try {
                searchRequest.setMinPrice(new BigDecimal(minPrice));
            } catch (NumberFormatException e) {
                // 忽略无效的价格值
            }
        }
        
        if (maxPrice != null && !maxPrice.isEmpty()) {
            try {
                searchRequest.setMaxPrice(new BigDecimal(maxPrice));
            } catch (NumberFormatException e) {
                // 忽略无效的价格值
            }
        }
        
        Page<CourseResponse> courses = courseService.searchCourses(searchRequest);
        return ApiResponse.success(courses);
    }
    
    /**
     * 获取单个课程详情接口
     * @param id 课程ID
     * @return 课程详情
     */
    @GetMapping("/{id}")
    public ApiResponse<CourseResponse> getCourse(@PathVariable Long id) {
        try {
            logger.info("开始获取课程详情，courseId: {}", id);
            CourseResponse course = courseService.getCourseById(id);
            logger.info("课程详情获取成功，courseId: {}, title: {}", id, course.getTitle());
            return ApiResponse.success(course);
        } catch (Exception e) {
            logger.error("获取课程详情失败，courseId: {}, error: {}", id, e.getMessage(), e);
            throw e; // 重新抛出异常，让全局异常处理器处理
        }
    }
    
    /**
     * 获取指定课程的课时列表接口
     * @param id 课程ID
     * @return 课时列表
     */
    @GetMapping("/{id}/lessons")
    public ApiResponse<List<LessonResponse>> getCourseLessons(@PathVariable Long id) {
        return ApiResponse.success(lessonService.getCourseLessons(id));
    }
    
    /**
     * 创建课程接口（教师或管理员权限）
     * @param request 课程创建请求参数
     * @param auth 认证信息，包含当前登录用户
     * @return 创建后的课程详情
     */
    @PostMapping
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<CourseResponse> createCourse(@Valid @RequestBody CourseRequest request, 
                                                  Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        return ApiResponse.success(courseService.createCourse(request, principal.getUserId()));
    }
    
    /**
     * 更新课程接口（教师或管理员权限）
     * @param id 要更新的课程ID
     * @param request 课程更新请求参数
     * @param auth 认证信息，包含当前登录用户
     * @return 更新后的课程详情
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<CourseResponse> updateCourse(@PathVariable Long id, 
                                                  @Valid @RequestBody CourseRequest request,
                                                  Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        return ApiResponse.success(courseService.updateCourse(id, request, principal.getUserId()));
    }
    
    /**
     * 下线课程接口（教师或管理员权限）
     * @param id 要下线的课程ID
     * @param auth 认证信息，包含当前登录用户
     * @return 操作结果
     */
    @PutMapping("/{id}/unpublish")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> unpublishCourse(@PathVariable Long id, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        courseService.unpublishCourse(id, principal.getUserId());
        return ApiResponse.success(null, "课程已下线");
    }

    /**
     * 删除课程接口（教师或管理员权限）
     * @param id 要删除的课程ID
     * @param auth 认证信息，包含当前登录用户
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> deleteCourse(@PathVariable Long id, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        courseService.deleteCourse(id, principal.getUserId());
        return ApiResponse.success(null, "删除成功");
    }
    
    /**
     * 为课程创建课时接口（教师或管理员权限）
     * @param id 课程ID
     * @param request 课时创建请求参数
     * @param auth 认证信息，包含当前登录用户
     * @return 创建后的课时详情
     */
    @PostMapping("/{id}/lessons")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<LessonResponse> createLesson(@PathVariable Long id,
                                                  @Valid @RequestBody LessonRequest request,
                                                  Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        return ApiResponse.success(lessonService.createLesson(id, request, principal.getUserId()));
    }
    
    /**
     * 更新课时接口（教师或管理员权限）
     * @param lessonId 要更新的课时ID
     * @param request 课时更新请求参数
     * @param auth 认证信息，包含当前登录用户
     * @return 更新后的课时详情
     */
    @PutMapping("/lessons/{lessonId}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<LessonResponse> updateLesson(@PathVariable Long lessonId,
                                                  @Valid @RequestBody LessonRequest request,
                                                  Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        return ApiResponse.success(lessonService.updateLesson(lessonId, request, principal.getUserId()));
    }
    
    /**
     * 删除课时接口（教师或管理员权限）
     * @param lessonId 要删除的课时ID
     * @param auth 认证信息，包含当前登录用户
     * @return 操作结果
     */
    @DeleteMapping("/lessons/{lessonId}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> deleteLesson(@PathVariable Long lessonId, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        lessonService.deleteLesson(lessonId, principal.getUserId());
        return ApiResponse.success(null, "删除成功");
    }
    
    /**
     * 发布课程接口（教师或管理员权限）
     * @param id 要发布的课程ID
     * @param auth 认证信息，包含当前登录用户
     * @return 发布后的课程详情
     */
    @PostMapping("/{id}/publish")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<CourseResponse> publishCourse(@PathVariable Long id, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        return ApiResponse.success(courseService.publishCourse(id, principal.getUserId()));
    }
}


